package com.shujia.day17.tcp;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class Client {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("localhost", 7777);
        try {
            OutputStream outputStream = socket.getOutputStream();
            InputStream inputStream = socket.getInputStream();
            // 启动了输入输出线程
            new ClientOutput("客户端输出线程", outputStream).start();
            new ClientInput("客户端输入线程:", inputStream).start();
            // 为了防止客户端的mian方法执行结束，导致程序终止，那么需要加上 while(true)
            while (true){}
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            socket.close();
        }
    }

    static class ClientOutput extends Thread {
        OutputStream outputStream;
        Scanner scanner;

        public ClientOutput(String name, OutputStream outputStream) {
            super(name);
            this.outputStream = outputStream;
            this.scanner = new Scanner(System.in);
            System.out.println("当前客户端的输出流线程启动完成...");
        }

        /*
            TODO:
                在该线程中，可以通过Scanner来获取控制台的输入信息，并且将输入数据，通过
                    Socket的输出流发送给服务端

         */
        @Override
        public void run() {
            System.out.println("输出流线程开始工作...");
            while (true) {
                try {
                    System.out.println("请输入您要发送的信息:");
                    if (scanner.hasNext()) {
                        String message = scanner.next();
                        // 将输入的信息进行输出
                        outputStream.write((message + "\n").getBytes());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    static class ClientInput extends Thread {
        InputStream inputStream;
        BufferedReader bufferedReader;

        public ClientInput(String name, InputStream inputStream) {
            super(name);
            this.inputStream = inputStream;
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        }

        @Override
        public void run() {
            String line = "";
            try {
                while ((line = bufferedReader.readLine()) != null) {
                    System.out.println(this.getName() + "接收:" + line);
                }
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        }
    }
}
